import { message } from 'ant-design-vue'
import axios from 'axios'

const request = axios.create({
  baseURL: '/api',
  timeout: 20000,
  withCredentials: true,
})

request.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

request.interceptors.response.use(
  (response) => {
    const { data } = response
    const msg = data.message
    if (data.code === 40100) {
      // 如果是登录失败，并且当前页面不是登录页面，则跳转到登录页面
      if (
        response.request.responseURL.includes('user/get/login') &&
        !window.location.pathname.includes('login')
      ) {
        message.warning('请先登录')
        const redirectUrl = window.location.pathname + window.location.search
        window.location.href = `/user/login?redirect=${encodeURIComponent(redirectUrl)}`
      }
      return response
    }
    if (data.code === 50000) {
      message.error('服务器异常，请稍后再试')
      const error = new Error(msg)
      return Promise.reject(error)
    }
    if (data.code === 40000) {
      message.error('错误,', msg)
      const error = new Error(msg)
      return Promise.reject(error)
    }
    return response
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default request
